package com.betterjr.modules.sys.security;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import javax.security.auth.Subject;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SSOTokenAuthenticationFilter extends BaseFormAuthenticationFilter {

    private static Logger logger = LoggerFactory.getLogger(SSOTokenAuthenticationFilter.class);

    private static final String TOKEN_PARAMETER = "token";

    private String failureUrl;

    @Override
    protected AuthenticationToken createToken(final ServletRequest request, final ServletResponse response) {
        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        final String tokenStr = httpRequest.getParameter(TOKEN_PARAMETER);

        byte[] bytes = Base64Utils.decodeFromString(tokenStr);
        String decodeToken = new String(bytes);
        String[] decodeTokenArr = decodeToken.split("\\.");

        if (decodeTokenArr.length != 3) {
            throw new AuthenticationException("invalidate token string");
        }

        // 到用户代码和单位代码
        final String userCode = new String(Base64Utils.decodeFromString(decodeTokenArr[0]));
        final String corpCode = new String(Base64Utils.decodeFromString(decodeTokenArr[1]));
        final Long timestamp = Long.valueOf(new String(Base64Utils.decodeFromString(decodeTokenArr[2])));
        // final Long timestamp = new Date().getTime();
        return new BetterSsoToken(userCode, corpCode, timestamp);
    }

    @Override
    protected boolean isLoginRequest(ServletRequest request, ServletResponse response) {
        return true;
    }

    @Override
    protected boolean isLoginSubmission(ServletRequest request, ServletResponse response) {
        final String tokenStr = WebUtils.getCleanParam(request, TOKEN_PARAMETER);
        return request instanceof HttpServletRequest && !StringUtils.isEmpty(tokenStr);
    }

    // @Override
    // protected boolean onLoginFailure(final AuthenticationToken token, final AuthenticationException ae, final
    // ServletRequest request, final ServletResponse response) {
    // final Subject subject = getSubject(request, response);
    // if (subject.isAuthenticated() || subject.isRemembered()) {
    // try {
    // issueSuccessRedirect(request, response);
    // } catch (final Exception e) {
    // logger.error("Cannot redirect to the default success url", e);
    // }
    // } else {
    // try {
    // WebUtils.issueRedirect(request, response, failureUrl);
    // } catch (final IOException e) {
    // logger.error("Cannot redirect to failure url : {}", failureUrl, e);
    // ; }
    // }
    // return true;
    // }
    //
    // public void setFailureUrl(final String failureUrl) {
    // this.failureUrl = failureUrl;
    // }
    //

    // protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
    // ServletResponse response) throws Exception {
    // // System.out.println("this onLoginSuccess");
    // // System.out.println(subject);
    // // super.onLoginSuccess(token, subject, request, response);
    // HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    // HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    // httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/better/frame/index.html");
    // return false;
    //
    // }
    @Override
    public String getSuccessUrl() {
        return "/frame/index.html";
    }
}